//
//  MaintenanceMgmtViewController.m
//  FMS
//
//  Created by Steven on 10/11/13.
//  Copyright (c) 2013 QGSVN. All rights reserved.
//

#import "MaintenanceMgmtViewController.h"
#import "MaintenanceTypeViewController.h"
#import "BuildingMgmtViewController.h"
#import "MaintenanceDetailedViewController.h"
#import "UIScrollView+ScrollView.h"

@interface MaintenanceMgmtViewController ()

@end

@implementation MaintenanceMgmtViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    maintenancePermissionDict = [userDefaults objectForKey:MAINTENANCE_PERMISSION];
    
    dictLanguage = [ApplicationDelegate.arrayLanguage objectAtIndex:0];
    
    self.navigationController.navigationBar.hidden = YES;
    
    //set text for labels
    //inspection segment
    _lbInspectionItem.text          = [dictLanguage objectForKey:@"maintenance-mgmt.inspection.item"];
    _lbInspectionServiceType.text   = [dictLanguage objectForKey:@"maintenance-mgmt.inspection.service-type"];
    _lbInspectionResult.text        = [dictLanguage objectForKey:@"maintenance-mgmt.inspection.result"];
    _lbInspectionStartingDate.text  = [dictLanguage objectForKey:@"maintenance-mgmt.inspection.starting-date"];
    _lbInspectionEndingDate.text    = [dictLanguage objectForKey:@"maintenance-mgmt.inspection.ending-date"];
    
    //maintenance segment
    _lbMaintenanceItemID.text       = [dictLanguage objectForKey:@"maintenance-mgmt.maintenance.item-id"];
    _lbMaintenanceItemType.text     = [dictLanguage objectForKey:@"maintenance-mgmt.maintenance.item-type"];
    _lbMaintenanceType.text         = [dictLanguage objectForKey:@"maintenance-mgmt.maintenance.type"];
    _lbMaintenanceStartingDate.text = [dictLanguage objectForKey:@"maintenance-mgmt.inspection.starting-date"];
    _lbMaintenanceEndingDate.text   = [dictLanguage objectForKey:@"maintenance-mgmt.inspection.ending-date"];
    _lbMaintenanceStatus.text       = [dictLanguage objectForKey:@"maintenance-mgmt.maintenance.status"];
    
//    _btnInspection.layer.borderWidth = 1;
//    _btnInspection.layer.borderColor = [UIColor whiteColor].CGColor;
//    
//    _btnMaintenance.layer.borderWidth = 1;
//    _btnMaintenance.layer.borderColor = [UIColor whiteColor].CGColor;
    
    //alloc 2 arrays: Inspection and Maintenance
    inspectionArray  = [NSMutableArray arrayWithCapacity:1];
    maintenanceArray = [NSMutableArray arrayWithCapacity:1];
    
    //set inspection segment button
    [_btnInspection setBackgroundImage:[UIImage imageNamed:@"btnLeft@2x.png"] forState:UIControlStateNormal];
    [_btnInspection setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_btnInspection setBackgroundImage:[UIImage imageNamed:@"btnLeftSelected.png"] forState:UIControlStateSelected];
    [_btnInspection setTitleColor:APPLE_BLUE_COLOR forState:UIControlStateSelected];
    
//    UIBezierPath *maskPath;
//    maskPath = [UIBezierPath bezierPathWithRoundedRect:_btnInspection.bounds byRoundingCorners:(UIRectCornerTopLeft | UIRectCornerBottomLeft) cornerRadii:CGSizeMake(5.0, 5.0)];
//    
//    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
//    maskLayer.frame = _btnInspection.bounds;
//    maskLayer.fillColor = [[UIColor whiteColor] CGColor];
//    maskLayer.path = maskPath.CGPath;
//    _btnInspection.layer.mask = maskLayer;
//    _btnInspection.layer.masksToBounds = YES;
    
    //set maintenance segment button
    [_btnMaintenance setBackgroundImage:[UIImage imageNamed:@"btnRight@2x.png"] forState:UIControlStateNormal];
    [_btnMaintenance setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_btnMaintenance setBackgroundImage:[UIImage imageNamed:@"btnRightSelected.png"] forState:UIControlStateSelected];
    [_btnMaintenance setTitleColor:APPLE_BLUE_COLOR forState:UIControlStateSelected];
    
//    maskPath = [UIBezierPath bezierPathWithRoundedRect:_btnMaintenance.bounds byRoundingCorners:(UIRectCornerTopRight | UIRectCornerBottomRight) cornerRadii:CGSizeMake(5.0, 5.0)];
//    
//    maskLayer = [[CAShapeLayer alloc] init];
//    maskLayer.frame = _btnMaintenance.bounds;
//    maskLayer.fillColor = [[UIColor whiteColor] CGColor];
//    maskLayer.backgroundColor = [[UIColor clearColor] CGColor];
//    maskLayer.path = maskPath.CGPath;
//    _btnMaintenance.layer.mask = maskLayer;
    
    
    _mainTableView.separatorColor = APPLE_BLUE_COLOR;
    
    currentSelectedIndex = inspection_tag;
    
    myActivityView = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(1024/2, 768/2, 25, 25)];
    myActivityView.hidesWhenStopped = YES;
    myActivityView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
    [self.view addSubview:myActivityView];
    [myActivityView startAnimating];
    
    //get permission of Inspection, if don't have permission, switch to Maintenance
    BOOL isAccessInspection = [[[maintenancePermissionDict objectForKey:@"inspection"] objectForKey:@"access"] boolValue];
    if (!isAccessInspection) {
        [self switchSegment:_btnMaintenance];
    }
    
    currentFilterMaintenanceIndex = 0;
}

- (void) doNothing {
    
}

- (void) viewWillAppear:(BOOL)animated {
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    int isSelectDetail = [[userDefaults objectForKey:@"isSelectDetail"] intValue];
    if (!isSelectDetail) {
        if (currentSelectedIndex == inspection_tag) {
            [self switchSegment:_btnInspection];
        }
        else {
            [self switchSegment:_btnMaintenance];
        }
    }
    [userDefaults setObject:[NSNumber numberWithInt:0] forKey:@"isSelectDetail"];
}

- (void) listInspection {
    [inspectionArray removeAllObjects];
    
    isLoadMore = NO;
    currentRecordIndex = 0;
    
    NSMutableArray *tmpArray;
    //MA và Owner view all equipment. Contractor chỉ view được những equipment mà nó add
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *role = [[userDefaults objectForKey:ACCOUNT_ROLE] lowercaseString];
    NSString *contractorId = [userDefaults objectForKey:ACCOUNT_ID];
    
    if ([role isEqualToString:@"ma"] || [role isEqualToString:@"owner"] || [role isEqualToString:@"admin"]) {
        tmpArray = [CouchBaseLiteLib listInspectionFrom:currentRecordIndex numberRow:NUMBER_ROW_PAGE];
    }
    else {
        tmpArray = [CouchBaseLiteLib listInspectionByContractor:contractorId from:currentRecordIndex numberRow:NUMBER_ROW_PAGE];
    }

    for (int i=0;i < [tmpArray count];i++) {
        NSMutableDictionary *dict = [tmpArray objectAtIndex:i];
        NSString *maintenanceId = [dict objectForKey:@"maintenanceId"] == nil ? @"" : [dict objectForKey:@"maintenanceId"];
        NSString *itemId = [dict objectForKey:@"itemId"] == nil ? @"" : [dict objectForKey:@"itemId"];
        
        double dateUpdated = [[dict objectForKey:@"dateUpdated"] doubleValue];
        //recreate input dictionary
        NSMutableDictionary *inputDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:[dict objectForKey:@"itemName"],@"itemName",[dictLanguage objectForKey:@"maintenance-mgmt.service-type.inspection"],@"serviceType",[dict objectForKey:@"startDate"],@"startDate",[dict objectForKey:@"lastDone"],@"lastDone",[dict objectForKey:@"checkList"],@"checkList",[dict objectForKey:@"technicalAssessment"],@"technicalAssessment",[dict objectForKey:@"report"],@"report",maintenanceId,@"maintenanceId",[dict objectForKey:@"_id"],@"_id",itemId,@"itemId",[dict objectForKey:@"scheduleId"],@"scheduleId",[NSNumber numberWithDouble:dateUpdated],@"dateUpdated",[dict objectForKey:@"workComplete"],@"workComplete",[dict objectForKey:@"inspectionResult"],@"inspectionResult",[dict objectForKey:@"followAction"],@"followAction", nil];
        
        //get schedule of this inspection
        CBLDocument *scheduleDoc = [[CouchBaseLiteLib sharedCouchBaseLite] getDocumentById:[dict objectForKey:@"scheduleId"]];
        @try {
            NSString *startDate  = [scheduleDoc.properties objectForKey:@"startDate"];
            NSString *lastUpdate = [scheduleDoc.properties objectForKey:@"lastUpdate"];
            [inputDict setObject:startDate forKey:@"startDate"];
            [inputDict setObject:lastUpdate forKey:@"lastUpdate"];
        }
        @catch (NSException *e) {
            NSLog(@"listInspection = %@",e);
        }
        
        [inspectionArray addObject:inputDict];
    }
    currentRecordIndex += [tmpArray count];
    
    if ([tmpArray count] == NUMBER_ROW_PAGE) {
        isLoadMore = YES;
    }
    else {
        isLoadMore = NO;
    }
    
    [self.mainTableView reloadData];
    
    if (isLoadMore) {
//        [self.mainTableView showLoadingMore];
    }
    else
        [self.mainTableView hideLoadingMore];
    [self.mainTableView hideActivity];
    [myActivityView stopAnimating];
}

- (void) listMoreInspection:(int)_newIndex {
//    dispatch_queue_t myQueue = dispatch_queue_create("com.myqgs.listMoreInspection", NULL);
//    dispatch_async(myQueue, ^(void) {
    
        NSMutableArray *tmpArray;
        //MA và Owner view all equipment. Contractor chỉ view được những equipment mà nó add
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        NSString *role = [[userDefaults objectForKey:ACCOUNT_ROLE] lowercaseString];
        NSString *contractorId = [userDefaults objectForKey:ACCOUNT_ID];
        
        if ([role isEqualToString:@"ma"] || [role isEqualToString:@"owner"] || [role isEqualToString:@"admin"]) {
            tmpArray = [CouchBaseLiteLib listInspectionFrom:currentRecordIndex numberRow:NUMBER_ROW_PAGE];
        }
        else {
            tmpArray = [CouchBaseLiteLib listInspectionByContractor:contractorId from:currentRecordIndex numberRow:NUMBER_ROW_PAGE];
        }
        
        for (int i=0;i < [tmpArray count];i++) {
            NSMutableDictionary *dict = [tmpArray objectAtIndex:i];
            NSString *maintenanceId = [dict objectForKey:@"maintenanceId"] == nil ? @"" : [dict objectForKey:@"maintenanceId"];
            NSString *itemId = [dict objectForKey:@"itemId"] == nil ? @"" : [dict objectForKey:@"itemId"];
            
            double dateUpdated = [[dict objectForKey:@"dateUpdated"] doubleValue];
            //recreate input dictionary
            NSMutableDictionary *inputDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:[dict objectForKey:@"itemName"],@"itemName",[dictLanguage objectForKey:@"maintenance-mgmt.service-type.inspection"],@"serviceType",[dict objectForKey:@"startDate"],@"startDate",[dict objectForKey:@"lastDone"],@"lastDone",[dict objectForKey:@"checkList"],@"checkList",[dict objectForKey:@"technicalAssessment"],@"technicalAssessment",[dict objectForKey:@"report"],@"report",maintenanceId,@"maintenanceId",[dict objectForKey:@"_id"],@"_id",itemId,@"itemId",[dict objectForKey:@"scheduleId"],@"scheduleId",[NSNumber numberWithDouble:dateUpdated],@"dateUpdated",[dict objectForKey:@"workComplete"],@"workComplete",[dict objectForKey:@"inspectionResult"],@"inspectionResult",[dict objectForKey:@"followAction"],@"followAction", nil];
            
            //get schedule of this inspection
            CBLDocument *scheduleDoc = [[CouchBaseLiteLib sharedCouchBaseLite] getDocumentById:[dict objectForKey:@"scheduleId"]];
            @try {
                NSString *startDate  = [scheduleDoc.properties objectForKey:@"startDate"];
                NSString *lastUpdate = [scheduleDoc.properties objectForKey:@"lastUpdate"];
                [inputDict setObject:startDate forKey:@"startDate"];
                [inputDict setObject:lastUpdate forKey:@"lastUpdate"];
            }
            @catch (NSException *e) {
                NSLog(@"listInspection = %@",e);
            }
            
            [inspectionArray addObject:inputDict];
        }
        
//        dispatch_async(dispatch_get_main_queue(), ^(void) {
            int previousIndex = currentRecordIndex;
            currentRecordIndex += [tmpArray count];
            
            if ([tmpArray count] == NUMBER_ROW_PAGE) {
                isLoadMore = YES;
            }
            else {
                isLoadMore = NO;
            }
            
            if (isLoadMore) {
//                [self.mainTableView showLoadingMore];
            }
            else
                [self.mainTableView hideLoadingMore];

            [self.mainTableView hideActivity];
            
            NSMutableArray *indexPaths = [[NSMutableArray alloc] init];
            for (int i=previousIndex;i < currentRecordIndex;i++) {
                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
                [indexPaths addObject:indexPath];
            }
            [self.mainTableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationAutomatic];
            
            //order by dateUpdated
//            [inspectionArray sortUsingDescriptors:[NSArray arrayWithObject:[[NSSortDescriptor alloc] initWithKey:@"dateUpdated" ascending:NO selector:@selector(compare:)]]];
//        });
//    });
#if !OS_OBJECT_USE_OBJC
//    dispatch_release(myQueue);
#endif
//    myQueue = nil;
}

- (void) listMaintenanceByType:(int)_maintenanceTypeId {
    [maintenanceArray removeAllObjects];
    
    currentRecordIndex = 0;
    
    if (!isLock) {
//        dispatch_queue_t myQueue = dispatch_queue_create("com.myqgs.listMaintenanceByType", NULL);
//        dispatch_async(myQueue, ^(void) {
            isLock = YES;
            
            NSMutableArray *tmpArray;
            //MA và Owner view all equipment. Contractor chỉ view được những equipment mà nó add
            NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
            NSString *role = [[userDefaults objectForKey:ACCOUNT_ROLE] lowercaseString];
            NSString *contractorId = [userDefaults objectForKey:ACCOUNT_ID];
            if ([role isEqualToString:@"ma"] || [role isEqualToString:@"owner"] || [role isEqualToString:@"admin"]) {
                tmpArray = [CouchBaseLiteLib listMaintenanceByType:_maintenanceTypeId from:currentRecordIndex numberRow:NUMBER_ROW_PAGE];
            }
            else {
                tmpArray = [CouchBaseLiteLib listMaintenanceByType:_maintenanceTypeId contractor:contractorId from:currentRecordIndex numberRow:NUMBER_ROW_PAGE];
            }
            
            for (int i=0;i < [tmpArray count];i++) {
                NSMutableDictionary *tmpDict = [[tmpArray objectAtIndex:i] mutableCopy];
                //get schedule info of this maintenance
                NSString *scheduleId = [tmpDict objectForKey:@"scheduleId"];
                CBLDocument *scheduleDoc = [CouchBaseLiteLib getDocumentById:scheduleId];
                NSString *startDate = [scheduleDoc propertyForKey:@"startDate"];
                NSString *endDate   = [scheduleDoc propertyForKey:@"lastUpdate"];
                NSString *roomValue = [scheduleDoc propertyForKey:@"room"];
                NSString *floorValue = [scheduleDoc propertyForKey:@"floor"];
                NSString *buildingValue = [scheduleDoc propertyForKey:@"building"];
                NSString *campValue = [scheduleDoc propertyForKey:@"camp"];
                NSString *unitValue = [scheduleDoc propertyForKey:@"unit"];
                
                NSString *itemName = [NSString stringWithFormat:@"%@, %@ ,%@, %@, %@",roomValue,floorValue,buildingValue,unitValue,campValue];
                
                @try {
                    [tmpDict setObject:itemName forKey:@"itemName"];
                    [tmpDict setObject:startDate forKey:@"startDate"];
                    [tmpDict setObject:endDate forKey:@"lastUpdate"];
                }
                @catch (NSException *e) {
                    NSLog(@"listMaintenanceByType = %@",e);
                }
                [maintenanceArray addObject:tmpDict];
            }
//            dispatch_async(dispatch_get_main_queue(), ^(void) {
                currentRecordIndex += [tmpArray count];
                
                if ([tmpArray count] == NUMBER_ROW_PAGE) {
                    isLoadMore = YES;
                }
                else {
                    isLoadMore = NO;
                }
                
                [self.mainTableView reloadData];
                
                isLock = NO;
                
                if (isLoadMore) {
//                    [self.mainTableView showLoadingMore];
                }
                else
                    [self.mainTableView hideLoadingMore];
                [self.mainTableView hideActivity];
                [myActivityView stopAnimating];
//            });
//        });
#if !OS_OBJECT_USE_OBJC
//        dispatch_release(myQueue);
#endif
//        myQueue = nil;
    }
}

- (void) listMoreMaintenanceByType:(int)_maintenanceTypeId {
    if (!isLock) {
//        dispatch_queue_t myQueue = dispatch_queue_create("com.myqgs.listMoreMaintenanceByType", NULL);
//        dispatch_async(myQueue, ^(void) {
            isLock = YES;
            
            NSMutableArray *tmpArray;
            //MA và Owner view all equipment. Contractor chỉ view được những equipment mà nó add
            NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
            NSString *role = [[userDefaults objectForKey:ACCOUNT_ROLE] lowercaseString];
            NSString *contractorId = [userDefaults objectForKey:ACCOUNT_ID];
            if ([role isEqualToString:@"ma"] || [role isEqualToString:@"owner"] || [role isEqualToString:@"admin"]) {
                tmpArray = [CouchBaseLiteLib listMaintenanceByType:_maintenanceTypeId from:currentRecordIndex numberRow:NUMBER_ROW_PAGE];
            }
            else {
                tmpArray = [CouchBaseLiteLib listMaintenanceByType:_maintenanceTypeId contractor:contractorId from:currentRecordIndex numberRow:NUMBER_ROW_PAGE];
            }
            
            for (int i=0;i < [tmpArray count];i++) {
                NSMutableDictionary *tmpDict = [[tmpArray objectAtIndex:i] mutableCopy];
                //get schedule info of this maintenance
                NSString *scheduleId = [tmpDict objectForKey:@"scheduleId"];
                CBLDocument *scheduleDoc = [CouchBaseLiteLib getDocumentById:scheduleId];
                NSString *startDate = [scheduleDoc propertyForKey:@"startDate"];
                NSString *endDate   = [scheduleDoc propertyForKey:@"lastUpdate"];
                NSString *roomValue = [scheduleDoc propertyForKey:@"room"];
                NSString *floorValue = [scheduleDoc propertyForKey:@"floor"];
                NSString *buildingValue = [scheduleDoc propertyForKey:@"building"];
                NSString *campValue = [scheduleDoc propertyForKey:@"camp"];
                NSString *unitValue = [scheduleDoc propertyForKey:@"unit"];
                
                NSString *itemName = [NSString stringWithFormat:@"%@, %@ ,%@, %@, %@",roomValue,floorValue,buildingValue,unitValue,campValue];
                
                @try {
                    [tmpDict setObject:itemName forKey:@"itemName"];
                    [tmpDict setObject:startDate forKey:@"startDate"];
                    [tmpDict setObject:endDate forKey:@"lastUpdate"];
                }
                @catch (NSException *e) {
                    NSLog(@"listMaintenanceByType = %@",e);
                }
                [maintenanceArray addObject:tmpDict];
            }
//            dispatch_async(dispatch_get_main_queue(), ^(void) {
                int previousIndex = currentRecordIndex;
                currentRecordIndex += [tmpArray count];
                
                if ([tmpArray count] == NUMBER_ROW_PAGE) {
                    isLoadMore = YES;
                }
                else {
                    isLoadMore = NO;
                }
                
                if (isLoadMore) {
//                    [self.mainTableView showLoadingMore];
                }
                else
                    [self.mainTableView hideLoadingMore];
                [self.mainTableView hideActivity];
                
                NSMutableArray *indexPaths = [[NSMutableArray alloc] init];
                for (int i=previousIndex;i < currentRecordIndex;i++) {
                    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
                    [indexPaths addObject:indexPath];
                }
                if ([indexPaths count] > 0) {
                    [self.mainTableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationAutomatic];
                }
                
                isLock = NO;
//            });
//        });
#if !OS_OBJECT_USE_OBJC
//        dispatch_release(myQueue);
#endif
//        myQueue = nil;
    }
}

- (IBAction)backPreviousView:(id)sender {
    [self dismissModalViewControllerAnimated:YES];
}

- (IBAction)switchSegment:(UIButton*)sender {
    [myActivityView startAnimating];
    [self.mainTableView reloadData];
    
    currentSelectedIndex = sender.tag;
    
    if (currentSelectedIndex == inspection_tag) {
        permissionDict = [maintenancePermissionDict objectForKey:@"inspection"];
        
        BOOL isAccess = [[permissionDict objectForKey:@"access"] boolValue];
        if (!isAccess) {
            UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.warning"] message:[dictLanguage objectForKey:@"general.permission.no-right-access"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
            [dialog show];
            
            //switch to Maintenance tab
            [self switchSegment:_btnMaintenance];
            
            return;
        }
        
        _btnFilter.hidden = YES;
        _inspectionContainerView.hidden = NO;
        _maintenanceContainerView.hidden = !_inspectionContainerView.hidden;
        
        [_btnInspection setSelected:YES];
        [_btnMaintenance setSelected:NO];
        
        [inspectionArray removeAllObjects];
    }
    else {
        permissionDict = [maintenancePermissionDict objectForKey:@"maintenance"];
        
        BOOL isAccess = [[permissionDict objectForKey:@"access"] boolValue];
        if (!isAccess) {
            UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.warning"] message:[dictLanguage objectForKey:@"general.permission.no-right-access"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
            [dialog show];
            
            //switch to Inspection tab
            [self switchSegment:_btnInspection];
            
            return;
        }
        
        _btnFilter.hidden = NO;
        _inspectionContainerView.hidden = YES;
        _maintenanceContainerView.hidden = !_inspectionContainerView.hidden;
        [_btnInspection setSelected:NO];
        [_btnMaintenance setSelected:YES];
        
        [maintenanceArray removeAllObjects];
    }
    [self.mainTableView reloadData];
    [self delayToSwitch];
}

- (void) delayToSwitch {
    if (currentSelectedIndex == inspection_tag) {
        [self listInspection];
    }
    else {
        [self listMaintenanceByType:currentFilterMaintenanceIndex];
    }
}

- (IBAction)handleAddNew:(id)sender {
    //use to check and reload data
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:[NSNumber numberWithInt:MaintenanceMgmt] forKey:SUPER_PARENT];
    
    MaintenanceTypeViewController *controller = [[MaintenanceTypeViewController alloc] initWithNibName:@"MaintenanceTypeViewController" bundle:nil serviceType:Inspection parent:self];
    UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:controller];
    navController.modalPresentationStyle = UIModalPresentationPageSheet;
    [self presentModalViewController:navController animated:YES];
    
    if (SYSTEM_VERSION_LESS_THAN(@"7.0"))
        navController.view.superview.frame = CGRectMake(300, 100, 400, 400);
}

- (IBAction)handleFilter:(UIButton*)sender {
    //init controller to filter value
    FilterViewController *controller = [[FilterViewController alloc] initWithStyle:UITableViewStylePlain filterType:filter_maintenance];
    controller.delegate = self;
    controller.currentSelectedIndex = currentFilterMaintenanceIndex;
    popoverController = [[UIPopoverController alloc] initWithContentViewController:controller];
    [popoverController presentPopoverFromRect:sender.frame inView:[sender superview] permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
}

#pragma mark scrollview load more
- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView{
    didReadyLoadMore = NO;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    float bottomEdge = scrollView.contentOffset.y + scrollView.frame.size.height;
    if (bottomEdge >= scrollView.contentSize.height && !didReadyLoadMore)
    {
        didReadyLoadMore = YES;
        
        if(!isLoadMore)
        {
            [self.mainTableView hideLoadingMore];
            return;
        }
//        [self.mainTableView showActivity];
        if (currentSelectedIndex == inspection_tag)
            [self listMoreInspection:currentRecordIndex];
        else
            [self listMoreMaintenanceByType:currentFilterMaintenanceIndex];
    }
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
//    if (didReadyLoadMore) {
//        if(!isLoadMore)
//        {
//            [self.mainTableView hideLoadingMore];
//            return;
//        }
//        [self.mainTableView showActivity];
//        if (currentSelectedIndex == inspection_tag)
//            [self listMoreInspection:currentRecordIndex];
//        else
//            [self listMoreMaintenance:currentRecordIndex];
//    }
}

#pragma mark FilterViewDelegate
- (void) didSelectFilter:(NSMutableDictionary *)filterDict {
    //do filter
    [popoverController dismissPopoverAnimated:YES];
    
    int maintenanceTypeId = [[filterDict objectForKey:@"index"] intValue];
    currentFilterMaintenanceIndex = maintenanceTypeId;
    
    [self listMaintenanceByType:maintenanceTypeId];
    
    [_mainTableView reloadData];
}

#pragma mark UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (currentSelectedIndex == inspection_tag)
        return [inspectionArray count];
    else
        return [maintenanceArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *cellIndentifier = @"CellIdentifier";
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentifier];
    NSMutableDictionary *dict;
    
    @try {
        if (currentSelectedIndex == inspection_tag){
            dict = [inspectionArray objectAtIndex:indexPath.row];
            
            UILabel *lbCellItem = [[UILabel alloc] initWithFrame:CGRectMake(30, 20, 223, 40)];
            lbCellItem.backgroundColor = [UIColor clearColor];
            lbCellItem.textColor = [UIColor darkGrayColor];
            lbCellItem.text = [dict objectForKey:@"itemName"];
            lbCellItem.lineBreakMode = NSLineBreakByTruncatingTail;
            [cell.contentView addSubview:lbCellItem];
            lbCellItem.numberOfLines = 2;
            [lbCellItem sizeToFit];
            
            UILabel *lbCellStartDate = [[UILabel alloc] initWithFrame:CGRectMake(375, 20, 220, 21)];
            lbCellStartDate.backgroundColor = [UIColor clearColor];
            lbCellStartDate.textColor = [UIColor darkGrayColor];
            lbCellStartDate.text = [NSDate stringFormatTimeDateFromDate:[NSDate dateFormatDateFullFromString:[dict objectForKey:@"startDate"]]];
            [cell.contentView addSubview:lbCellStartDate];
            
            UILabel *lbCellEndDate = [[UILabel alloc] initWithFrame:CGRectMake(650, 20, 220, 21)];
            lbCellEndDate.backgroundColor = [UIColor clearColor];
            lbCellEndDate.textColor = [UIColor darkGrayColor];
            lbCellEndDate.text = [NSDate stringFormatTimeDateFromDate:[NSDate dateFormatDateFullFromString:[dict objectForKey:@"lastUpdate"]]];
            [cell.contentView addSubview:lbCellEndDate];
        }
        else {
            dict = [maintenanceArray objectAtIndex:indexPath.row];
            
            UILabel *lbCellItem = [[UILabel alloc] initWithFrame:CGRectMake(30, 20, 220, 40)];
            lbCellItem.backgroundColor = [UIColor clearColor];
            lbCellItem.textColor = [UIColor darkGrayColor];
            lbCellItem.text = [dict objectForKey:@"itemName"];
            lbCellItem.lineBreakMode = NSLineBreakByTruncatingTail;
            [cell.contentView addSubview:lbCellItem];
            lbCellItem.numberOfLines = 2;
            [lbCellItem sizeToFit];
            
            UILabel *lbCellItemType = [[UILabel alloc] initWithFrame:CGRectMake(289, 20, 128, 21)];
            lbCellItemType.backgroundColor = [UIColor clearColor];
            lbCellItemType.textColor = [UIColor darkGrayColor];
            //        lbCellItemType.text = [dict objectForKey:@"itemType"];
            [cell.contentView addSubview:lbCellItemType];
            
            int itemType = [[dict objectForKey:@"itemType"] intValue];
            switch (itemType) {
                case Building_Type:
                    lbCellItemType.text = [dictLanguage objectForKey:@"schedule.title-building"];
                    break;
                default:
                    lbCellItemType.text = [dictLanguage objectForKey:@"schedule.title-equipment"];
                    break;
            }
            
            UILabel *lbCellMaintenanceType = [[UILabel alloc] initWithFrame:CGRectMake(452, 20, 140, 40)];
            lbCellMaintenanceType.backgroundColor = [UIColor clearColor];
            lbCellMaintenanceType.textColor = [UIColor darkGrayColor];
            
            //assign maintenance type title for
            int maintenanceType = [[dict objectForKey:@"maintenanceTypeId"] intValue];
            lbCellMaintenanceType.text = [ApplicationDelegate getMaintenanceName:maintenanceType];
            
            [cell.contentView addSubview:lbCellMaintenanceType];
            lbCellMaintenanceType.numberOfLines = 0;
            [lbCellMaintenanceType sizeToFit];
            
            //        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            //        [dateFormatter setDateFormat:@"hh:mm a - MMM dd, yyyy"];
            //
            //        NSTimeInterval startDateInterval = [[dict objectForKey:@"startDate"] doubleValue];
            //        NSTimeInterval endDateInterval = [[dict objectForKey:@"endDate"] doubleValue];
            //        NSDate *startDate = [NSDate dateWithTimeIntervalSince1970:startDateInterval];
            //        NSDate *endDate = [NSDate dateWithTimeIntervalSince1970:endDateInterval];
            
            UILabel *lbCellStartDate = [[UILabel alloc] initWithFrame:CGRectMake(662, 20, 220, 21)];
            lbCellStartDate.backgroundColor = [UIColor clearColor];
            lbCellStartDate.textColor = [UIColor darkGrayColor];
            lbCellStartDate.text = [NSDate stringFormatTimeDateFromDate:[NSDate dateFormatDateFullFromString:[dict objectForKey:@"startDate"]]];
            [cell.contentView addSubview:lbCellStartDate];
            
            //        UILabel *lbCellEndDate = [[UILabel alloc] initWithFrame:CGRectMake(717, 20, 220, 21)];
            //        lbCellEndDate.backgroundColor = [UIColor clearColor];
            //        lbCellEndDate.textColor = [UIColor darkGrayColor];
            //        lbCellEndDate.text = [dict objectForKey:@"lastUpdate"];
            //        [cell.contentView addSubview:lbCellEndDate];
            
            UILabel *lbCellStatus = [[UILabel alloc] initWithFrame:CGRectMake(925, 20, 100, 40)];
            lbCellStatus.backgroundColor = [UIColor clearColor];
            lbCellStatus.textColor = [UIColor darkGrayColor];
            [cell.contentView addSubview:lbCellStatus];
            
            int status = [[dict objectForKey:@"status"] intValue];
            lbCellStatus.text = [ApplicationDelegate getMaintenanceStatus:status];
            lbCellStatus.numberOfLines = 0;
            [lbCellStatus sizeToFit];
        }
    }
    @catch (NSException *e) {
        NSLog(@"%@",e);
    }
    
    return cell;
}

#pragma mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:[NSNumber numberWithInt:MaintenanceMgmt] forKey:SUPER_PARENT];
    [userDefaults setObject:[NSNumber numberWithInt:1] forKey:@"isSelectDetail"];
    
    if (currentSelectedIndex == inspection_tag) {
        NSMutableDictionary *dict = [inspectionArray objectAtIndex:indexPath.row];
        
        MaintenanceDetailedViewController *controller = [[MaintenanceDetailedViewController alloc] initWithNibName:@"MaintenanceDetailedViewController" bundle:nil parent:self serviceType:Inspection];
        controller.isEdit = YES;
        controller.itemDetailDict = dict;
        
        //get item document (room/equipment)
        CBLDocument *itemDoc = [CouchBaseLiteLib getDocumentById:[dict objectForKey:@"itemId"]];
        NSMutableDictionary *itemDict = [itemDoc.properties mutableCopy];
        
        @try {
            [controller.itemDetailDict setObject:[itemDict objectForKey:@"_id"] forKey:@"itemId"];
            NSString *itemName = [itemDict objectForKey:@"item_name"] == nil ? [itemDict objectForKey:@"name"] : [itemDict objectForKey:@"item_name"];
            [controller.itemDetailDict setObject:itemName forKey:@"item_name"];
            [controller.itemDetailDict setObject:[itemDict objectForKey:@"building"] forKey:@"building"];
            [controller.itemDetailDict setObject:[itemDict objectForKey:@"camp"] forKey:@"camp"];
            [controller.itemDetailDict setObject:[itemDict objectForKey:@"floor"] forKey:@"floor"];
            [controller.itemDetailDict setObject:[itemDict objectForKey:@"service"] forKey:@"service"];
            [controller.itemDetailDict setObject:[itemDict objectForKey:@"unit"] forKey:@"unit"];
            [controller.itemDetailDict setObject:[itemDict objectForKey:@"Table"] forKey:@"Table"];
            
            NSString *room = [itemDict objectForKey:@"room"] == nil ? @"":[itemDict objectForKey:@"room"];
            NSString *description = [itemDict objectForKey:@"description"] == nil ? @"":[itemDict objectForKey:@"description"];
            NSString *system = [itemDict objectForKey:@"system"] == nil ? @"":[itemDict objectForKey:@"system"];
            
            [controller.itemDetailDict setObject:room forKey:@"room"];
            [controller.itemDetailDict setObject:description forKey:@"description"];
            [controller.itemDetailDict setObject:system forKey:@"system"];
        }
        @catch (NSException *e) {
            NSLog(@"%@",e);
        }
        
        [self.navigationController pushViewController:controller animated:YES];
    }
    else {
        
        NSMutableDictionary *dict = [maintenanceArray objectAtIndex:indexPath.row];
        
        MaintenanceDetailedViewController *controller = [[MaintenanceDetailedViewController alloc] initWithNibName:@"MaintenanceDetailedViewController" bundle:nil parent:self serviceType:Maintenance];
        controller.isEdit = YES;
        
        int maintenanceType = [[dict objectForKey:@"maintenanceTypeId"] intValue];
        NSString *maintenanceName = [ApplicationDelegate getMaintenanceName:maintenanceType];
        
        //set current maitenance selected type
        [userDefaults setObject:[NSNumber numberWithInt:maintenanceType] forKey:CURRENT_SELECTED_MAINTENANCE_TYPE];
        
        controller.itemDetailDict = dict;
        [controller.itemDetailDict setObject:[dict objectForKey:@"maintenanceTypeId"] forKey:@"itemType"];
        [controller.itemDetailDict setObject:maintenanceName forKey:@"itemName"];
        [self.navigationController pushViewController:controller animated:YES];
        [self performSelector:@selector(delaySelectDetailedMaintenance:) withObject:controller.itemDetailDict afterDelay:0.2];
        
    }
}

- (void) delaySelectDetailedMaintenance:(NSMutableDictionary*)_dict {
    MaintenanceDetailedViewController *controller = [self.navigationController.viewControllers lastObject];
    [controller confirmMaintenanceType:_dict itemDetailedDict:controller.itemDetailDict];
    
    //set view status with this role
    controller.titleContainerView.frame = CGRectMake(_titleContainerView.frame.origin.x, _titleContainerView.frame.origin.y, _titleContainerView.frame.size.width, 1);
    controller.btnInspection.hidden = controller.btnMaintenance.hidden = YES;
    
    [controller checkStatusOfDetail];
}

- (void) confirmSelectType:(NSMutableDictionary*)dict {
    //save current selected service type
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:[dict objectForKey:@"serviceType"] forKey:SELECTED_SERVICE_TYPE];
    
    BuildingMgmtViewController *controller;
    controller = [[BuildingMgmtViewController alloc] initWithNibName:@"BuildingMgmtViewController" bundle:nil itemType:Building_Type];
    controller.parent = self;
    controller.serviceType = [[dict objectForKey:@"serviceType"] intValue];
    
    [self.navigationController pushViewController:controller animated:NO];
}

- (void) dealloc {
    NSLog(@"%@ dealloc",self);
}

@end
